package com.nix.web.controller.file;

import org.apache.commons.io.FileUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;


/**
 * Create by zhangpe0312@qq.com on 2017/12/12.
 */
@Controller
public class UploadAction{

    @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    public String upload(HttpServletRequest request,
                         @RequestParam("description") String description,
                         @RequestParam("file") MultipartFile file,
                         Model model) {
        System.out.println("文件描述：" + description);
        if (file != null) {
            //上传文件路径
            String path = request.getServletContext().getRealPath("/src/main/dataFile/uploadFile/textFile/excel");
            System.out.println("path :" + path);
            //上传文件名
            String fileName = file.getOriginalFilename();
            System.out.println("fileName :" + fileName);
            File filePath = new File(path, fileName);
            //如果路径不存在就创建一个
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            try {
                file.transferTo(new File(path + File.separator + fileName));
                System.out.println(path + File.separator + fileName);
                model.addAttribute("result ", "upload success");
            } catch (IOException e) {
                e.printStackTrace();
                model.addAttribute("result  ", "upload fail");
            }
        }
        model.addAttribute("page", "value");
        return "/app/file/uploadResult";
    }

    @RequestMapping(value = "/download/do")
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                           @RequestParam("filename") String filename,
                                           Model model) throws Exception {
        //下载文件路径
        String path = request.getServletContext().getRealPath("/src/main/dataFile/uploadFile/textFile/excel");
        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
}
